package pl.edu.pw.stud.ltrzaska.policy.xml;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import pl.edu.pw.stud.ltrzaska.policy.entity.FilesystemObject;
import pl.edu.pw.stud.ltrzaska.policy.entity.FilesystemTime;
import pl.edu.pw.stud.ltrzaska.policy.entity.PolicyValidator;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;

public class ConverterCommons {
	private static final Logger LOGGER = Logger.getLogger(ConverterCommons.class);

	static void preLoopUnmarshal(HierarchicalStreamReader reader, FilesystemObject fs) {
		if (fs.getRefname() == null) {
			String refname = reader.getAttribute("refname");
			if (refname != null && refname.length() > 0) {
				fs.setRefname(refname);
			} else {
				throw new ConversionException("Atrybut refName jest obligatoryjny.");
			}
		}
	}

	static void inLoopUnmarshal(HierarchicalStreamReader reader, UnmarshallingContext context, FilesystemObject obj) {
		String attrName = reader.getNodeName();
		if ("name".equals(attrName)) {
			obj.setName(reader.getValue());
		} else if ("inherits".equals(attrName)) {
			obj.setInherits(reader.getValue());
		} else if ("update-time".equals(attrName)) {
			obj.setUpdateTime((FilesystemTime) context.convertAnother(obj, FilesystemTime.class));
		} else if ("create-time".equals(attrName)) {
			obj.setCreateTime((FilesystemTime) context.convertAnother(obj, FilesystemTime.class));
		} else if ("min-size".equals(attrName)) {
			obj.setMinSize(reader.getValue());
		} else if ("max-size".equals(attrName)) {
			obj.setMaxSize(reader.getValue());
		} else if ("file-extension".equals(attrName)) {
			obj.setFileExtension(reader.getValue());
		} else if ("add-validators".equals(attrName)) {
			obj.setAdditionalValidators((ArrayList<PolicyValidator>) context.convertAnother(obj, List.class));
			for(PolicyValidator pv : obj.getAdditionalValidators()) {
				obj.getAdditionalValidatorsNames().add(pv.getName());
			}
		} else if ("system-properties".equals(attrName)) {
			obj.setSystemProperties(reader.getValue());
		} else if ("owner".equals(attrName)) {
			obj.setOwnerRefName(reader.getValue());
		} else if ("existence".equals(attrName)) {
		 	String val = reader.getValue();
		 	if(FilesystemObject.EXISTENCE_DEFAULT.equals(val) || FilesystemObject.EXISTENCE_FORBIDDEN.equals(val) || FilesystemObject.EXISTENCE_OBLIGATORY.equals(val)) {
		 		obj.setExistence(val);
		 	} else {
		 		throw new ConversionException(new StringBuffer("Nieznana wartosc dla atrybutu existence: ").append(val).toString());	
		 	}
		} else {
			obj.addAdditionalAttribtue(attrName, reader.getValue());
		}
	}
}
